package com.whpost.service.service.t;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.t.TFilesMapper;
import com.whpost.service.dao.t.TMenuDao;
import com.whpost.service.dao.t.TPermissionDao;
import com.whpost.service.dao.t.TRoleDao;
import com.whpost.service.entity.t.*;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: Yin Zhuoyi
 * @Date: 2021/12/15 11:16
 */
@Service
public class TPermissionServices extends BaseServices<TPermissionDao, TPermission> {

    @Resource
    private TRoleDao tRoleDao;
    @Resource
    private TMenuServices tMenuServices;
    @Resource
    private TApiNonceService tApiNonceService;

    public List<String> getPercodes(String loginId){
        List<String> rtnList = new ArrayList<>();;   //可以分配的权限列表
        TCzy tCzy = new TCzy();
        tCzy = gettCzyDao().selectById(loginId);
        if ("1".equals(loginId)){
            rtnList = getBaseMapper().getPerCode(new QueryWrapper<TPermission>().eq("state","1"));
        }else{
            String pers="";
            pers = tRoleDao.selectById(tCzy.getRoleId()).getPermissionId();
            List<String> perlist = Arrays.asList(pers.split(","));
            //ToolBean.info("获取到的pers:"+pers);
            rtnList = getBaseMapper().getPerCode(new QueryWrapper<TPermission>().eq("state","1").in("id",perlist));
        }
        return rtnList;
    }

    public String getPermissionCode(String id){
        return getBaseMapper().selectById(id).getCode();
    }

    public boolean addPermission(TMenu tmenu) {

        try {

            Map<String, String> pMap = new HashMap<>();

            pMap.put("add", "增加");
            pMap.put("del", "删除");
            pMap.put("update", "修改");
            pMap.put("query", "查询");
            TPermission tPermission = new TPermission();
            Long sl = getBaseMapper().selectCount(new QueryWrapper<TPermission>().eq("menu_id", tmenu.getId()));
            if (sl > 0) {
                //修改权限代码
                List<TPermission> tPermissionList = new ArrayList<>();
                tPermissionList = getBaseMapper().selectList(new QueryWrapper<TPermission>().eq("menu_id", tmenu.getId()));
                for (int i=0;i<tPermissionList.size();i++){
                    tPermission = new TPermission();
                    tPermission =tPermissionList.get(i);
                    String code = tPermission.getCode();
                    if (code.indexOf("add")>=0) code=tmenu.getQxdm()+":add";
                    else if (code.indexOf("update")>=0) code=tmenu.getQxdm()+":update";
                    else if (code.indexOf("del")>=0) code=tmenu.getQxdm()+":del";
                    else if (code.indexOf("query")>=0) code=tmenu.getQxdm()+":query";
                    tPermission.setCode(code);
                    tPermission.setZjm(code);
                    getBaseMapper().updateById(tPermission);
                }
                return true;
            } else {
                //新增
                String bz = tmenu.getQxdm();
                for (Map.Entry<String, String> entry : pMap.entrySet()) {
                    // 处理元素
                    tPermission = new TPermission();
                    tPermission.setMenuId(tmenu.getId());
                    tPermission.setName(tmenu.getName() + entry.getValue());
                    tPermission.setZjm(bz + ":" + entry.getKey());
                    tPermission.setCode(bz + ":" + entry.getKey());
                    getBaseMapper().insert(tPermission);
                }
                return true;
            }
        } catch (Exception e) {
            ToolBean.info("addPermission发生错误：" + e.toString());
            return false;
        }
    }

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<TPermission> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TPermission> tPermissionListInfo = new ListInfo<>();
            QueryWrapper<TPermission> tPermissionQueryWrapper = new QueryWrapper<TPermission>();
            if (!StringUtils.isEmpty(cxmc)){
                tPermissionQueryWrapper.like("name",cxmc);
            }else{
                tPermissionQueryWrapper.eq("1","1");
            }
            tPermissionQueryWrapper.orderByDesc("id");

            IPage<TPermission> tPermissionIPage = getBaseMapper().selectPage(page,tPermissionQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(tPermissionIPage.getTotal());
            pageInfo.setCurPage(tPermissionIPage.getCurrent());
            pageInfo.setPageSize(tPermissionIPage.getSize());
            pageInfo.setPageTotal(tPermissionIPage.getPages());

            tPermissionListInfo.setPageInfo(pageInfo);
            tPermissionListInfo.setListInfo(tPermissionIPage.getRecords());
            tPermissionListInfo.setUserId(loginId);

            //查询条件的值
            Map<String,Object> cxtjMap = new HashMap<>();
            cxtjMap.put("cxmc",cxmc);

            //返回前端的内容
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("cxjg",tPermissionListInfo);
            rtnMap.put("cxtj",cxtjMap);

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map){
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            Map<String,Object> rtnMap = new HashMap<>();

            if ("1".equals(lx)){
                TPermission tPermission = new TPermission();
                tPermission = getBaseMapper().selectById(id);
                rtnMap.put("tPermission",tPermission);
            }

            List<TreeNode> menuTree = tMenuServices.getTreeSelectDisParent();   //禁用父节点
            rtnMap.put("menuTree",menuTree);

            ResultInfo resultInfo = new ResultInfo(0, "查询成功！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",qxmc="",qxdm="",menu="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("qxmc")) {
                qxmc = jsonObject.getString("qxmc");
            }
            if (jsonObject.containsKey("qxdm")) {
                qxdm = jsonObject.getString("qxdm");
            }
            if (jsonObject.containsKey("menu")) {
                menu = jsonObject.getString("menu");
            }

            if (StringUtils.isEmpty(menu)){
                ResultInfo resultInfo = new ResultInfo(500, "没有选择对应的菜单！",null);
                return backRtn(resultInfo,loginId);
            }

            if (StringUtils.isEmpty(qxdm) || StringUtils.isEmpty(qxmc)){
                ResultInfo resultInfo = new ResultInfo(500, "代码或名称不能为空！",null);
                return backRtn(resultInfo,loginId);
            }

            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"menu.addDo");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TPermission tPermission = new TPermission();
            if ("1".equals(lx)){
                tPermission = getBaseMapper().selectById(id);
            }
            tPermission.setName(qxmc);
            tPermission.setZjm(qxdm);
            tPermission.setCode(qxdm);
            tPermission.setMenuId(Long.parseLong(menu));

            ResultInfo resultInfo;
            Map<String,Object> rtnMap = new HashMap<>();

            if ("1".equals(lx)){
                getBaseMapper().updateById(tPermission);
                resultInfo = new ResultInfo(2, "修改成功！",rtnMap);
            }else{
                getBaseMapper().insert(tPermission);
                resultInfo = new ResultInfo(1, "新增成功！",rtnMap);
            }
            return backRtn(resultInfo,loginId);
        }
    }
}
